<?php

/**
 * This is the model class for table "{{resource_group}}".
 *
 * The followings are the available columns in table '{{resource_group}}':
 * @property integer $_id
 * @property integer $parent_id
 * @property string $name
 * @property string $classname
 * @property integer $rating
 * @property string $picture
 * @property string $description
 * @property integer $space_id
 * @property integer $app_id
 * @property integer $status
 */
class BSMResourceGroup extends CActiveRecord
{
    static $use4AllApp = true;
    
    const SPORT_TYPE = 2;
    const AREA = 3;
    const STADIUM = 4;
    
	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{resource_group}}';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('parent_id, rating, space_id, app_id, status', 'numerical', 'integerOnly'=>true),
			array('name, classname', 'length', 'max'=>45),
			array('picture, description', 'length', 'max'=>255),
			// The following rule is used by search().
			// @todo Please remove those attributes that should not be searched.
			array('_id, parent_id, name, classname, rating, picture, description, space_id, app_id, status', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
            'parent'=>array(self::BELONGS_TO, 'BSMResourceGroup', 'parent_id'),
            'children'=>array(self::HAS_MANY, 'BSMResourceGroup', 'parent_id'),
            'members'=>array(self::HAS_MANY, 'BSMResourceGroupMember', 'group_id'),
            'favorites'=>array(self::HAS_MANY, 'BSMUserFavoriteGroup', 'group_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'_id' => 'ID',
			'parent_id' => 'Parent',
			'name' => 'Name',
			'classname' => 'Classname',
			'rating' => 'Rating',
			'picture' => 'Picture',
			'description' => 'Description',
			'space_id' => 'Space',
			'app_id' => 'App',
			'status' => 'Status',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 *
	 * Typical usecase:
	 * - Initialize the model fields with values from filter form.
	 * - Execute this method to get CActiveDataProvider instance which will filter
	 * models according to data in model fields.
	 * - Pass data provider to CGridView, CListView or any similar widget.
	 *
	 * @return CActiveDataProvider the data provider that can return the models
	 * based on the search/filter conditions.
	 */
	public function search()
	{
		// @todo Please modify the following code to remove attributes that should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('_id',$this->_id);
		$criteria->compare('parent_id',$this->parent_id);
		$criteria->compare('name',$this->name,true);
		$criteria->compare('classname',$this->classname,true);
		$criteria->compare('rating',$this->rating);
		$criteria->compare('picture',$this->picture,true);
		$criteria->compare('description',$this->description,true);
		$criteria->compare('space_id',$this->space_id);
		$criteria->compare('app_id',$this->app_id);
		$criteria->compare('status',$this->status);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}

	/**
	 * @return CDbConnection the database connection used for this class
	 */
	public function getDbConnection()
	{
		return Yii::app()->bookingdb;
	}

	/**
	 * Returns the static model of the specified AR class.
	 * Please note that you should have this exact method in all your CActiveRecord descendants!
	 * @param string $className active record class name.
	 * @return BSMResourceGroup the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}
    
    public function getStadiumListByUser($userId, $limit = 0)
    {
        $criteria = new CDbCriteria;
        $criteria->with = array(
            'favorites',
        );
        $criteria->addCondition("parent_id = :parent_id");
        $criteria->params[':parent_id'] = self::findByConstantId(self::STADIUM)->_id;
        
        $criteria->addCondition("favorites.user_id = :userId");  
        $criteria->params[':userId'] = $userId;
        if ($limit > 0) {
            $criteria->limit = $limit;
        }
        $criteria->distinct = true;
        $criteria->together = true;
        
        $list = self::model()->findAll($criteria);
        
        return $list;
    }

    public function getStadiumListByRating($limit)
    {
        $criteria = new CDbCriteria;
        
        $criteria->addCondition("parent_id = :parent_id");
        $criteria->params[':parent_id'] = self::findByConstantId(self::STADIUM)->_id;
        
        $criteria->order = 'rating DESC';
        $criteria->limit = $limit;
        
        $list = self::model()->findAll($criteria);
        
        return $list;
    }

    public function getSportTypeByStadium($stadiumId)
    {
        $stadium = self::model()->findByPk($stadiumId);
        if ($stadium == null) {
            return array();
        }
        
        $members = $stadium->members;
        $memberIds = array();
        foreach ($members as $member) {
            $memberIds[] = $member->member_id;
        }
        
        $criteria = new CDbCriteria;
        $criteria->with = array(
            'members',
        );
        $criteria->addInCondition("members.member_id", $memberIds);
        $criteria->addCondition("parent_id = :parent_id");
        $criteria->params[':parent_id'] = self::findByConstantId(self::SPORT_TYPE)->_id;
        $criteria->distinct = true;
        
        $list = self::model()->findAll($criteria);
        
        return $list;
    }
    
    public function getSportTypes()
    {
        $criteria = new CDbCriteria;
        $criteria->addCondition("parent_id = :parent_id");
        $criteria->params[':parent_id'] = self::findByConstantId(self::SPORT_TYPE)->_id;
        
        $list = self::model()->findAll($criteria);
        
        return $list;
    }
    
    public function getAreaListData($id, $name)
    {
        $criteria = new CDbCriteria;
        $criteria->addCondition("parent_id = :parent_id");
        $criteria->params[':parent_id'] = self::findByConstantId(self::AREA)->_id;
        
        $list = self::model()->findAll($criteria);
        $result = array();
        foreach ($list as $item) {
            $result[$item->{$id}] = $item->{$name};
            $this->getSubAreaListData($result, $id, $name, $item->children);
        }
        
        return $result;
    }
    
    function getSubAreaListData(&$result, $id, $name, $list, $space = '--')
    {
        foreach ($list as $item) {
            $result[$item->{$id}] = $space.$item->{$name};
            $this->getSubAreaListData($result, $id, $name, $item->children, $space.'--');
        }
    }
    
    public function getAllChildren($id)
    {
        $criteria = new CDbCriteria;
        $criteria->addCondition("parent_id = :parent_id");
        $criteria->params[':parent_id'] = $id;
        
        $list = self::model()->findAll($criteria);
        $result = array();
        foreach ($list as $item) {
            $result[] = $item;
            
            $this->add2AllChildrenList($result, $item->children);
        }
        
        return $result;
    }
    
    function add2AllChildrenList(&$result, $list)
    {
        foreach ($list as $item) {
            $result[] = $item;
            
            $this->add2AllChildrenList($result, $item->children);
        }
    }
    
    public function getStadiumsBySportType($sportTypeId, $name = NULL)
    {
        $params = array(':sportTypeId'=>$sportTypeId);
        
        $sql = "SELECT DISTINCT t.* FROM " . $this->tableName() .
                " t INNER JOIN {{resource_group_member}} m" .
                " ON t._id = m.group_id WHERE t.parent_id = " .
                self::findByConstantId(self::STADIUM)->_id;
        
        if (!Controller::IsNullOrEmptyString($name)) {
            $sql .= " AND t.name LIKE :name ";
            $params["name"] = '%' . $name . '%';
        }
        
        $sql .= " AND m.member_id IN (SELECT m1.member_id FROM " . $this->tableName() .
                " t1 INNER JOIN {{resource_group_member}} m1" .
                " ON t1._id = m1.group_id WHERE t1._id = :sportTypeId)";
        
        return self::model()->findAllBySql($sql, $params);
    }
    
    public function getStadiumList($area, $sportType)
    {
        $params = array();
        
        $sql = "SELECT DISTINCT t.* FROM " . $this->tableName() .
                " t INNER JOIN {{resource_group_member}} m" .
                " ON t._id = m.group_id WHERE t.parent_id = " .
                self::findByConstantId(self::STADIUM)->_id;
        
        if (!Controller::isNullOrEmptyString($area)) {
            $list = $this->getAllChildren($area);
            $areas = array($area);
            foreach ($list as $item) {
                $areas[] = $item->_id;
            }
            
            //$params['areas'] = implode(",", $areas);
            $sql .= " AND m.member_id IN (SELECT m1.member_id FROM " . $this->tableName() .
                    " t1 INNER JOIN {{resource_group_member}} m1" .
                    " ON t1._id = m1.group_id WHERE t1._id IN (" . implode(",", $areas) . "))";
        }
        
        if (!Controller::isNullOrEmptyString($sportType)) {
            $params['sportType'] = $sportType;
            $sql .= " AND m.member_id IN (SELECT m1.member_id FROM " . $this->tableName() .
                    " t1 INNER JOIN {{resource_group_member}} m1" .
                    " ON t1._id = m1.group_id WHERE t1._id = :sportType)";
        }
        
        return self::model()->findAllBySql($sql, $params);
    }
    
    static function findByConstantId($cid) {
        if (self::$use4AllApp) {
            return BSMResourceGroup::model()->findByPk($cid);
        }
        
        $spaceId = Blyn::app()->getActiveSpace()->getId();
        $appId = Blyn::app()->getActiveApp()->getId();

        $name = NULL;
        switch ($cid) {
            case self::SPORT_TYPE:
                $name = 'Sport Type';
                break;
            case self::AREA:
                $name = 'Area';
                break;
            case self::STADIUM:
                $name = 'Sport Stadium';
                break;

            default:
                break;
        }
        
        if ($name == NULL) {
            return NULL;
        } else {
            return BSMResourceGroup::model()->findByAttributes(
                    array('space_id'=>$spaceId, 'app_id'=>$appId, 'name'=>$name));
        }
    }
    
    function udateRating($id)
    {
        
    }
}
